/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package me.liangjun.inspectionresults.service.impl;

import lombok.RequiredArgsConstructor;
import me.liangjun.inspectionresults.domain.InspectionDiagnosis;
import me.liangjun.inspectionresults.domain.InspectionResults;
import me.liangjun.inspectionresults.repository.InspectionDiagnosisRepository;
import me.liangjun.inspectionresults.repository.InspectionResultsRepository;
import me.liangjun.inspectionresults.service.InspectionDiagnosisService;
import me.liangjun.inspectionresults.service.dto.InspectionDiagnosisDto;
import me.liangjun.inspectionresults.service.dto.InspectionDiagnosisQueryCriteria;
import me.liangjun.inspectionresults.service.dto.InspectionResultsDto;
import me.liangjun.inspectionresults.service.mapstruct.InspectionDiagnosisMapper;
import me.liangjun.inspectionresults.service.mapstruct.InspectionResultsMapper;
import me.zhengjie.utils.FileUtil;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.QueryHelp;
import me.zhengjie.utils.ValidationUtil;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @author wei
 * @website https://el-admin.vip
 * @description 服务实现
 * @date 2022-01-16
 **/
@Service
@RequiredArgsConstructor
public class InspectionDiagnosisServiceImpl implements InspectionDiagnosisService {

    private final InspectionDiagnosisRepository inspectionDiagnosisRepository;
    private final InspectionResultsRepository inspectionResultsRepository;
    private final InspectionDiagnosisMapper inspectionDiagnosisMapper;
    private final InspectionResultsMapper inspectionResultsMapper;

    @Override
    public Map<String, Object> queryAll(InspectionDiagnosisQueryCriteria criteria, Pageable pageable) {
        Page<InspectionDiagnosis> page = inspectionDiagnosisRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        return PageUtil.toPage(page.map(inspectionDiagnosisMapper::toDto));
    }

    @Override
    public List<InspectionDiagnosisDto> queryAll(InspectionDiagnosisQueryCriteria criteria) {
        return inspectionDiagnosisMapper.toDto(inspectionDiagnosisRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }

    @Override
    @Transactional
    public InspectionDiagnosisDto findById(Long id) {
        InspectionDiagnosis inspectionDiagnosis = inspectionDiagnosisRepository.findById(id).orElseGet(InspectionDiagnosis::new);
        ValidationUtil.isNull(inspectionDiagnosis.getId(), "InspectionDiagnosis", "id", id);
        return inspectionDiagnosisMapper.toDto(inspectionDiagnosis);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public InspectionDiagnosisDto create(InspectionDiagnosisDto resources) {
        InspectionDiagnosis inspectionDiagnosis = inspectionDiagnosisMapper.toEntity(resources);
        List<String> name = resources.getName();
        List<InspectionResultsDto> nameDto = resources.getNameDto();
        List<InspectionResults> results = new ArrayList<>();
        for (String s : name) {
            if(s.isEmpty()){
                continue;
            }
            for (InspectionResultsDto dto : nameDto) {
                if (dto.getType() == Integer.parseInt(s)) {
                    InspectionResults entry = inspectionResultsRepository.findByPidAndType(dto.getPId(), dto.getType());
                    if(entry!=null){
                        entry.copy(inspectionResultsMapper.toEntity(dto));
                        results.add(entry);
                    }else{
                        results.add(inspectionResultsMapper.toEntity(dto));
                    }
                }
            }
        }
        List<String> name2 = resources.getName2();
        List<InspectionResultsDto> name2Dto = resources.getName2Dto();
        for (String s : name2) {
            if(s.isEmpty()){
                continue;
            }
            for (InspectionResultsDto dto : name2Dto) {
                if (dto.getType() == Integer.parseInt(s)) {
                    InspectionResults entry = inspectionResultsRepository.findByPidAndType(dto.getPId(), dto.getType());
                    if(entry!=null){
                        entry.copy(inspectionResultsMapper.toEntity(dto));
                        results.add(entry);
                    }else{
                        results.add(inspectionResultsMapper.toEntity(dto));
                    }
                }
            }
        }
        List<String> name3 = resources.getName3();
        List<InspectionResultsDto> name3Dto = resources.getName3Dto();
        for (String s : name3) {
            if(s.isEmpty()){
                continue;
            }
            for (InspectionResultsDto dto : name3Dto) {
                if (dto.getType() == Integer.parseInt(s)) {
                    InspectionResults entry = inspectionResultsRepository.findByPidAndType(dto.getPId(), dto.getType());
                    if(entry!=null){
                        entry.copy(inspectionResultsMapper.toEntity(dto));
                        results.add(entry);
                    }else{
                        results.add(inspectionResultsMapper.toEntity(dto));
                    }
                }
            }
        }
        inspectionResultsRepository.saveAll(results);
        InspectionDiagnosis one = inspectionDiagnosisRepository.findByPid(resources.getPId());
        if (one != null) {
            inspectionDiagnosis = inspectionDiagnosisMapper.toEntity(resources);
            one.copy(inspectionDiagnosis);
            inspectionDiagnosisRepository.save(one);
        }else {
            inspectionDiagnosisRepository.save(inspectionDiagnosis);
        }
        return resources;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(InspectionDiagnosisDto resources) {
        InspectionDiagnosis inspectionDiagnosis = inspectionDiagnosisRepository.findById(resources.getId()).orElseGet(InspectionDiagnosis::new);
        ValidationUtil.isNull(inspectionDiagnosis.getId(), "InspectionDiagnosis", "id", resources.getId());
        inspectionDiagnosis = inspectionDiagnosisMapper.toEntity(resources);

        inspectionDiagnosis.copy(inspectionDiagnosis);
        inspectionDiagnosisRepository.save(inspectionDiagnosis);
    }

    @Override
    public void deleteAll(Long[] ids) {
        for (Long id : ids) {
            inspectionDiagnosisRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<InspectionDiagnosisDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (InspectionDiagnosisDto inspectionDiagnosis : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("pID", inspectionDiagnosis.getPId());
            map.put("术后肌无力危象", inspectionDiagnosis.getName());
            map.put("术后肌无力危象", inspectionDiagnosis.getName2());
            map.put("术后肌无力危象", inspectionDiagnosis.getName3());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public InspectionDiagnosisDto findByPid(Long pid) {
        InspectionDiagnosis diagnosis = inspectionDiagnosisRepository.findByPid(pid);
        List<InspectionResults> byPid = inspectionResultsRepository.findByPid(pid);
        List<InspectionResults> nameDto = new ArrayList<>();
        List<InspectionResults> name2Dto = new ArrayList<>();
        List<InspectionResults> name3Dto = new ArrayList<>();
        for (InspectionResults results : byPid) {
            if (results.getType() < 8) {
                nameDto.add(results);
            } else if (results.getType() > 17) {
                name3Dto.add(results);
            } else {
                name2Dto.add(results);
            }
        }
        InspectionDiagnosisDto dto = inspectionDiagnosisMapper.domain2dto(diagnosis, nameDto, name2Dto, name3Dto);
        return dto;
    }
}